package org.alfresco.dbencrypt;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 
 * @author rjmfernandes@gmail.com
 * 
 */
@SuppressWarnings("restriction")
public class SimpleEncryptor {

	private static final String ALGORITHM = "AES";
	private static final byte[] CRYPT_KEY = "debug discovers.".getBytes();

	public static String encrypt(String Data) throws InvalidKeyException,
			NoSuchAlgorithmException, NoSuchPaddingException,
			IllegalBlockSizeException, BadPaddingException {
		Cipher cipher = getCipher(Cipher.ENCRYPT_MODE);
		byte[] encVal = cipher.doFinal(Data.getBytes());
		return new BASE64Encoder().encode(encVal);
	}

	public static String decrypt(String encryptedData)
			throws IllegalBlockSizeException, BadPaddingException,
			InvalidKeyException, NoSuchAlgorithmException,
			NoSuchPaddingException, IOException {
		Cipher cipher = getCipher(Cipher.DECRYPT_MODE);
		byte[] decodedValue = new BASE64Decoder().decodeBuffer(encryptedData);
		byte[] decValue = cipher.doFinal(decodedValue);
		return new String(decValue);
	}

	private static Cipher getCipher(int mode) throws NoSuchAlgorithmException,
			NoSuchPaddingException, InvalidKeyException {
		Key key = new SecretKeySpec(CRYPT_KEY, ALGORITHM);
		Cipher c = Cipher.getInstance(ALGORITHM);
		c.init(mode, key);
		return c;
	}

	@SuppressWarnings("static-access")
	public static void main(String[] args) {
		try {
			SimpleEncryptor test = new SimpleEncryptor();
			String paswordEnc = test.encrypt(args[0]);
			String passwordDec = test.decrypt(paswordEnc);
			System.out.println(paswordEnc + ":" + passwordDec);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
